package io.traveller.user.webapp.controller;

import io.traveller.apiGateway.client.annotation.RouteURL;
import io.traveller.apiGateway.client.constants.SecurityLevel;
import io.traveller.user.webapp.entity.User;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 用户Controller
 *
 * Created by yunai on 16/9/11.
 */
@RestController
@RequestMapping("/user")
@RouteURL
public class UserController {

    private static final Map<Long, User> USERS = new HashMap<>();

    static {
        User user1 = new User(1L, "username001", "password001", "小红");
        USERS.put(user1.getId(), user1);
        User user2 = new User(2L, "username002", "password002", "小明");
        USERS.put(user1.getId(), user2);
        User user3 = new User(3L, "username003", "password003", "丁丁");
        USERS.put(user1.getId(), user3);
        User user4 = new User(4L, "username004", "password004", "冬冬");
        USERS.put(user1.getId(), user4);
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @RouteURL
    public User info(@RequestParam("id") Long id) {
        if (true) {
            User user = new User(0L, "拉拉", "password", "hahah");
            return user;
        }
        return USERS.get(id);
    }

    @RequestMapping(value = "/me", method = RequestMethod.GET)
    @RouteURL(securityLevel = SecurityLevel.USER_LOGIN)
    public User me(@RequestHeader("id") Long id) {
        return USERS.get(id);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @RouteURL(securityLevel = SecurityLevel.USER_LOGIN)
    public Long add(User user) {
        Random random = new Random();
        user.setId(random.nextLong());
        USERS.put(user.getId(), user);
        return user.getId();
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @RouteURL(securityLevel = SecurityLevel.USER_LOGIN)
    public void update(User user) {
        throw new UnsupportedOperationException("暂时不支持该操作!");
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @RouteURL(securityLevel = SecurityLevel.USER_LOGIN)
    public void delete(@RequestParam("id") Long id) {
        USERS.remove(id);
    }

}